package com.mooc.fileServlet;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;
import com.mooc.dao.FileDaoTest;
import com.mooc.entity.FileMessage;

/**
 * Servlet implementation class FileUpDownServlet
 */
@WebServlet("/test/fileupLoad")
public class FileUpDownServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getParameter("methodName");
		// 根据method的名字 来测试三个接口
		if (method.equals("up")) {
			upFile(request, response);
		} else if (method.equals("down")) {
			downFile(request, response);
		} else {
			getYuanData(request, response);
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 将post请求 交给doget去处理 完全是个人习惯
		doGet(request, response);
	}

	/**
	 * 返回响应参数
	 *
	 * @throws Exception
	 */
	private void sendResponse(String responseString, HttpServletResponse response) {
		// 响应信息 json字符串格式
		Map<String, Object> responseMap = new HashMap<String, Object>();
		responseMap.put("flag", true);
		responseMap.put("uuid", responseString);
		System.out.println("返回的值是" + responseString);
		// 生成响应的json字符串
		String jsonResponse = JSONObject.toJSONString(responseMap);
		System.out.println(jsonResponse);
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
			pw.write(jsonResponse);
			pw.flush();
		} catch (Exception e) {
		} finally {
			IOUtils.close(pw);
		}
	}

	// 文件上传
	private void upFile(HttpServletRequest request, HttpServletResponse resp) {
		FileDaoTest todb = new FileDaoTest();// 与数据库进行关联
		String fileName = request.getParameter("fileName");// 从request域请求中拿到文件名
		String randomUUID = UUID.randomUUID().toString();// 生成UUID作为文件名
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");// 时间格式
																	// yyyyMMdd
		String format2 = format.format(date);// 存到数据库里面的时间戳
		String fileFullPath = "E:/ABC/" + randomUUID + format2 + fileName;// 文件的存储路径
		int length = 0;// 文件大小
		String type = fileName.substring(fileName.indexOf("."));// 获取文件的类型
		InputStream input = null;
		FileOutputStream fos = null;
		try {
			input = request.getInputStream();
			File file = new File(fileFullPath);
			if (!file.exists()) {
				file.mkdirs();
			}
			fos = new FileOutputStream(file);
			int size = 0;
			byte[] buffer = new byte[1024];
			while ((size = input.read(buffer, 0, 1024)) != -1) {
				length += size;
				fos.write(buffer, 0, size);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 将相关的参数存储到数据库中
		// 参数1 UUID值，2文件大小，3文件类型，4文件名字，5文件创建时间，6，绝对路径
		todb.fileTodb(randomUUID, length, type, fileName, format2, "E:/ABC/" + fileFullPath);

		sendResponse(randomUUID, resp);// 将UUId 返回给客户端
	}

	// 文件下载
	private void downFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String uuid = req.getParameter("uuid");// 获取UUID
		FileDaoTest todb = new FileDaoTest();
		FileMessage file = todb.findFileByUUid(uuid);
		if (file == null) {
			sendResponse("HttpURLConnection.HTTP_GONE", resp);
			return;
		}
		File file2 = new File(file.getDirectory());
		BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file2));
		ServletOutputStream out = resp.getOutputStream();
		byte[] data = new byte[1024];
		int count = -1;
		while ((count = buf.read(data)) != -1) {
			out.write(data, 0, count);
		}
		buf.close();
		out.close();
	}

	// 获取json格式的源文件
	public void getYuanData(HttpServletRequest req, HttpServletResponse resp) {
		String uuid = req.getParameter("uuid");// 获取UUID
		FileDaoTest todb = new FileDaoTest();
		FileMessage file = todb.findFileByUUid(uuid);//从数据库中根据UUID 查询
		if (file == null) {
			sendResponse("HttpURLConnection.HTTP_GONE,错误代号410", resp);
			return;
		}
		StringBuilder builder = new StringBuilder();
		File file2 = new File(file.getDirectory());
		BufferedInputStream buf = null;
		ServletOutputStream out = null;
		try {
			buf = new BufferedInputStream(new FileInputStream(file2));
			out = resp.getOutputStream();
			byte[] data = new byte[1024];
			int count = -1;
			while ((count = buf.read(data)) != -1) {
				builder.append(new String(data, 0, count));
			}
			buf.close();
			out.close();
		} catch (Exception e) {
			sendResponse("HttpURLConnection.HTTP_GONE,错误代号410", resp);
		}
	}
}
